using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class LevelManager : MonoBehaviour
{
    public static LevelManager instance;
    public static GameObject ChooseBlock;

    NavMeshSurface meshSurface;

    int coinNum = 0;

    [HideInInspector]
    public bool cameraMoving;

    public List<BlockBase> blocks;

    public bool alreadyShare = false;

    private void Awake()
    {
        instance = this;
        meshSurface = GetComponent<NavMeshSurface>();
        meshSurface.layerMask = LayerMask.GetMask("Block");
        Application.targetFrameRate = 60;
        blocks = new List<BlockBase>();
        MessageManager.BindAction(MsgKey.Win, WinGame);
    }

    private void Start()
    {
        GameManager.SetAudioEnable();
        meshSurface.BuildNavMesh();

        //TimeAction.Delay(1, () => { VideoRecorder.BeginRecord(); });
        
    }

    void OnDestroy()
    {
        //VideoRecorder.EndRecord();
    }

    void WinGame()
    {
        GameManager.UnlockLevel(GameManager.CurLevel+1);
        print("unlock level");
    }

    public void BuildNavMesh()
    {
        meshSurface.BuildNavMesh();
    }

    public void AddCoinNum()
    {
        coinNum++;
    }

    public void SubCoinNum()
    {
        coinNum--;
        if (coinNum <= 0)
        {
            MessageManager.Run(MsgKey.OpenGate);
        }
    }

    public BlockBase FindLastBlock(Vector3 pos, BlockBase self)
    {
        List<BlockBase> blocksTemp = new List<BlockBase>();

        for(int i=0; i<blocks.Count; i++)
        {
            if (blocks[i] == null) continue;
            if (blocks[i].transform.position == pos && blocks[i].gameObject!= self.gameObject)
            {
                blocksTemp.Add(blocks[i]);
            }
        }

        float maxVal = 0;
        int index = 0;
        if(blocksTemp.Count==0) return null;
        for (int i = 0; i < blocksTemp.Count; i++)
        {
            if(CameraController.cameralook == CameraLook.Right)
            {
                if (blocksTemp[i].OrigPos.x>maxVal)
                {
                    maxVal = blocksTemp[i].OrigPos.x;
                    index = i;
                }
            }
            else if (CameraController.cameralook == CameraLook.Top)
            {
                if (blocksTemp[i].OrigPos.y > maxVal)
                {
                    maxVal = blocksTemp[i].OrigPos.y;
                    index = i;
                }
            }
            else if (CameraController.cameralook == CameraLook.Forward)
            {
                if (-blocksTemp[i].OrigPos.z > -maxVal)
                {
                    maxVal = blocksTemp[i].OrigPos.z;
                    index = i;
                }
            }
            else
            {
                return null;
            }
        }
        return blocksTemp[index];
    }
}
